<template>
  <div class="comment">
    <!-- 输入框 -->
    <van-field
      class="my-field"
      v-model="message"
      rows="2"
      autosize
      label="发表评论"
      type="textarea"
      maxlength="50"
      placeholder="请输入评论"
      show-word-limit
      ref="messageRef"
    />
    <van-button
      type="primary"
      class="my-post"
      block
      @click="postComment"
    >提交评论</van-button>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      offset="30"
      @load="onLoad"
    >
      <van-card
        v-for="item in comments"
        :key="item.id"
        :desc="item.content"
      >
        <template #title>
          <van-rate
            v-model="item.rate"
            readonly
          />
        </template>
        <template #thumb>
          <div class="icon-box">
            <van-icon name="manager" />
          </div>
          <div>Svip{{item.user_name}}</div>
        </template>
        <template #price>
          {{item.add_time | datefmt}}
        </template>
      </van-card>
    </van-list>
  </div>
</template>
<script>
export default {
  props: ['id'],
  data: () => ({
    message: '',
    page: 0,
    pageSize: 6,
    comments: [],
    hasMore: false,
    loading: false,
    finished: false,
    count: 0
  }),
  created() {
    // this.id = this.$route.params.id
  },
  methods: {
    async onLoad() {
      // setTimeout(async () => {
      // 异步请求数据并赋值
      await this.getComments()
      // 加载状态结束
      this.loading = false
      // 数据全部加载完成
      if (this.comments.length >= this.count) {
        this.finished = true
      }
      // }, 500)
    },
    async getComments() {
      if (this.hasMore !== false) return
      this.page++
      const res = await this.$http.getComments({ id: this.id, page: this.page, pageSize: this.pageSize })
      // 把总条数保存到  data 中
      this.count = res.count
      this.comments = this.comments.concat(res.message)
      this.hasMore = this.page * this.pageSize > res.count
    },
    getMore() {
      this.getComments()
    },
    async postComment() {
      await this.$http.postComment({ id: this.id, content: this.message })
      this.comments.unshift({
        add_time: new Date().getTime(),
        user_name: '匿名用户',
        rate: 5,
        content: this.message
      })
      this.message = ''
      this.$refs.messageRef.focus()
    }
  },
  computed: {
    moreText() {
      return this.hasMore ? '被掏空了' : '加载更多'
    }
  }
}
</script>
<style lang="less" >
.comment {
  .my-field {
    border: 1px solid #ddd;
    margin-top: 14px;
  }
  .my-post {
    margin: 14px 0;
  }
  .icon-box {
    width: 30px;
    height: 30px;
    line-height: 30px;
    padding: 4px;
    border: 1px solid #ddd;
    border-radius: 100%;
    text-align: center;
    .van-icon {
      font-size: 28px;
    }
  }
  .van-card__price {
    color: #969799;
  }
  .van-card__content {
    min-height: 60px;
  }
  .van-card__thumb {
    height: 60px;
  }
}
</style>